<?php

namespace app\api\Logic\Campusclass;

use app\api\model\CampusClassModel;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

//班级接口
class CampusClassLogic
{
    /**
     * 根据课程反向查询班级ID
     * @param $shopId
     * @param $courseIds
     * @return array
     */
    public function getClassByCourseIds($shopId,$courseIds){
        //todo 忘记tp写法，因此这边暂时用原生查询，后期完善
        $sql = "select id,name,is_choose,course_id from ss_campus_class where shop_id = {$shopId} and ( ";

        $where = "";
        foreach ($courseIds as $courseId){
            $where .= " FIND_IN_SET({$courseId},course_id) or";
        }
        $sql .= $where;
        $sql = substr($sql,0,-2);
        $sql .= ")";

        $list = Db::query($sql);
        return objToArray($list) ?? [];
    }

    /**
     * 获取班级详情
     * @param $shopId
     * @param $classId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getInfo($shopId,$classId){
        $info = CampusClassModel::where('shop_id',$shopId)
            ->where('id',$classId)
            ->find();
        return objToArray($info) ?? [];
    }

    /**
     * 创建一对一班级
     * @param $params
     * @return int|string
     */
    public function createOneOnOneClass($params){
        return CampusClassModel::insertGetId([
            'shop_id' => $params['shop_id'],
            'name' => $params['name'],
            'class_type' => 2,
            'course_id' => $params['course_id'],
            'class_size' => 1,
            'is_excess' => 0,
            'num' => 1,
            'create_time' => time()
        ]);
    }

    /**
     * 获取班级列表
     * @param $params
     * @param false $isLimit
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getList($params,$isLimit = false){
        $query = CampusClassModel::where('shop_id',$params['shop_id']);

        //根据课程类型筛选
        if(isset($params['class_type'])){
            $query = $query->where('class_type',$params['class_type']);
        }

        //分页
        if($isLimit){
            $list = $query->paginate(PAGE_SIZE);
            $res = objToArray($list) ?? [];
        }else{
            $list = $query->select();
            $res['data'] = objToArray($list) ?? [];
        }

        return $res;
    }
}
